
package com.sskj.market.ui.activity;

import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bulong.rudeness.RudenessScreenHelper;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.sskj.common.base.App;
import com.sskj.common.box.decoration.DividerLineItemDecoration;
import com.sskj.common.rxbus2.RxBus;
import com.sskj.common.rxbus2.Subscribe;
import com.sskj.common.rxbus2.ThreadMode;
import com.sskj.common.util.ClickUtil;
import com.sskj.common.util.ToastUtil;
import com.sskj.lib.RConfig;
import com.sskj.lib.base.BaseActivity;
import com.sskj.lib.bean.UserData;
import com.sskj.lib.model.room.UserViewModel;
import com.sskj.lib.util.AppCircleCheckUtil;
import com.sskj.market.R;
import com.sskj.market.R2;
import com.sskj.market.bean.AddressBean;
import com.sskj.market.bean.MyAddressBean;
import com.sskj.market.component.DaggerUserDataComponent;
import com.sskj.market.presenter.MyAddressPresenter;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;

/**
 * @author Hey
 * Create at  2019/07/26
 */
@Route(path = RConfig.MARKET_My_ADDRESS)
public class MyAddressActivity extends BaseActivity<MyAddressPresenter> {

    @BindView(R2.id.tvTitle)
    TextView tvTitle;
    @BindView(R2.id.tvReturn)
    TextView tvReturn;
    @BindView(R2.id.ivBack)
    LinearLayout ivBack;
    @BindView(R2.id.tvRight)
    TextView tvRight;
    @BindView(R2.id.ivRight)
    ImageView ivRight;
    @BindView(R2.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R2.id.smartRefreshLayout)
    SmartRefreshLayout smartRefreshLayout;

    List<MyAddressBean.DataBean> data;
    private int page = 1;
    private MyAddressAdapter addressAdapter;

    @Inject
    UserViewModel userViewModel;
    UserData userData;

    @Override
    public int getLayoutId() {
        return R.layout.market_activity_my_address;
    }

    @Override
    public MyAddressPresenter getPresenter() {
        return new MyAddressPresenter();
    }

    @Override
    public void initView() {
        DaggerUserDataComponent.create().inject(this);
        userViewModel.getUsers().observe(this, users -> {
            if (users != null && users.size() > 0) {
                userData = users.get(0);
            } else {
                userData = null;
            }
        });
        tvTitle.setText(App.INSTANCE.getString(R.string.market_myAddressActivity1));
        tvReturn.setVisibility(View.VISIBLE);
        tvRight.setVisibility(View.VISIBLE);
        tvRight.setText(App.INSTANCE.getString(R.string.market_myAddressActivity2));
        tvRight.setTextColor(getResources().getColor(R.color.lib_618));

        //添加收获地址
        ClickUtil.click(300, tvRight, () -> {
            ARouter.getInstance().build(RConfig.MARKET_ADD_ADDRESS).navigation();
        });

        data = new ArrayList<>();
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.addItemDecoration(new DividerLineItemDecoration(this)
                .setLeftPadding((int) RudenessScreenHelper.pt2px(App.INSTANCE, 30))
                .setRightPadding((int) RudenessScreenHelper.pt2px(App.INSTANCE, 30))
                .setPaintWidth((int) RudenessScreenHelper.pt2px(App.INSTANCE, 1))
                .setDividerColor(ContextCompat.getColor(App.INSTANCE, R.color.super_divi_split))
        );

        addressAdapter = new MyAddressAdapter();
        addressAdapter.bindToRecyclerView(recyclerView);
        addressAdapter.setEmptyView(R.layout.market_address_empty);
        RxBus.getDefault().register(this);

    }

    @Override
    public void initData() {
        mPresenter.getMyAddress(page, true);
    }


    @Override
    protected void initEvent() {
        super.initEvent();

        //添加收获地址
        ClickUtil.click(300, tvRight, () -> {
            if (AppCircleCheckUtil.checkLogin(this, userData)) {
                ARouter.getInstance().build(RConfig.MARKET_ADD_ADDRESS).navigation();
            }
        });

        smartRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshLayout) {
                page++;
                mPresenter.getMyAddress(page, false);
            }

            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                page = 1;
                data.clear();
                mPresenter.getMyAddress(page, false);
            }
        });

        addressAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            int i = view.getId();
            if (i == R.id.rlMoRen) {
                //设置默认地址
                if (data.get(position).getIs_default() == 1) {
                    ToastUtil.showShort(App.INSTANCE.getString(R.string.market_myAddressActivity3));
                } else {
                    mPresenter.setDetailAddress(data.get(position).getId());
                }
            } else if (i == R.id.tvBiAnJi) {
                //编辑地址信息
                ARouter.getInstance().build(RConfig.MARKET_EDITOR_DETAIL_ADDRESS).withInt("Id", data.get(position).getId()).navigation();

            } else if (i == R.id.tvCancel) {
                //删除地址信息
                if (data.get(position).getIs_default() == 1) {
                    ToastUtil.showShort(App.INSTANCE.getString(R.string.market_myAddressActivity4));
                } else {
                    mPresenter.onDeleteAddress(data.get(position).getId());
                }

            }
        });
        addressAdapter.setOnItemClickListener((adapter, view, position) -> {
            itemClick(position);
        });
    }

    /**
     * 选择地址回到订单页面
     * <p>
     * {@link  com.sskj.market.ui.activity.SubmitOrderActivity#getAddressInfo(AddressBean)}
     */
    private void itemClick(int position) {
        MyAddressBean.DataBean da = data.get(position);
        AddressBean addressBean = new AddressBean(da.getId(), da.getUid(), da.getName(), da.getPhone(),
                da.getProvince(), da.getCity(), da.getCountry(), da.getDetail(), da.getIs_default());
        RxBus.getDefault().post(addressBean);
        finish();
    }

    public void getAddressSuccess(MyAddressBean myAddressBean) {
        if (smartRefreshLayout.isLoading()) {
            smartRefreshLayout.finishLoadMore();
        }
        if (smartRefreshLayout.isRefreshing()) {
            smartRefreshLayout.finishRefresh();
        }
        if (myAddressBean == null) {
            return;
        }
        List<MyAddressBean.DataBean> tempData = myAddressBean.getData();
        data.addAll(tempData);
        addressAdapter.setNewData(data);
        addressAdapter.notifyDataSetChanged();

    }


    public void onDeleteAddressSuccess() {
        page = 1;
        data.clear();
        mPresenter.getMyAddress(page, true);
    }

    public void setDetailAddressSuccess() {
        page = 1;
        data.clear();
        mPresenter.getMyAddress(page, true);
    }

    class MyAddressAdapter extends BaseQuickAdapter<MyAddressBean.DataBean, BaseViewHolder> {
        private MyAddressAdapter() {
            super(R.layout.market_my_address_item, data);
        }

        @Override
        protected void convert(BaseViewHolder helper, MyAddressBean.DataBean item) {
            helper.setText(R.id.tvAddressName, item.getName())
                    .setText(R.id.tvAddressNumber, item.getPhone())
                    .setText(R.id.tvAddressItem, item.getProvince() + item.getCity() + item.getCountry() + item.getDetail())
                    .setImageResource(R.id.cbAddress, item.getIs_default() == 1 ? R.drawable.market_xuanzhong_icon : R.drawable.market_weixuanze)
                    .addOnClickListener(R.id.tvBiAnJi)
                    .addOnClickListener(R.id.tvCancel)
                    .addOnClickListener(R.id.rlMoRen);
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshList(MyAddressBean bean) {
        page = 1;
        data.clear();
        mPresenter.getMyAddress(page, true);
    }
}
